<template>
  <div class="doctor-selection">
    <div class="page-header">
      <h2>当前科室：{{ departmentName }} , 请选择医生</h2>
      <div class="action-buttons">
        <el-button class="back-button" @click="goBack">
          <el-icon><Back /></el-icon>
          返回科室选择
        </el-button>
      </div>
    </div>

    <div class="doctor-buttons">
      <div
        class="button-row"
        v-for="(row, rowIndex) in buttonRows"
        :key="rowIndex"
      >
        <el-button
          v-for="doctor in row"
          :key="doctor.id"
          class="doctor-button"
          @click="selectDoctor(doctor)"
        >
          <div class="button-content">
            <div class="avatar-container">
              <img
                :src="doctor.avatar"
                :alt="doctor.name"
                class="doctor-avatar"
              />
              <div
                class="online-indicator"
                :class="{ online: doctor.isOnline }"
              ></div>
            </div>
            <div class="button-text">
              <div class="doctor-name">{{ doctor.name }}</div>
              <div class="doctor-title">{{ doctor.title }}</div>
              <div class="doctor-status">
                <div class="remaining-container">
                  <span class="remaining-label">剩余号源:</span>
                  <span
                    class="remaining-count"
                    :class="{ low: doctor.remainingCount < 5 }"
                  >
                    {{ doctor.remainingCount }}个
                  </span>
                </div>
              </div>
            </div>
          </div>
        </el-button>
      </div>
    </div>

    <div class="pagination-controls" v-if="totalPages > 1">
      <el-button
        class="page-button prev-button"
        :disabled="currentPage === 1"
        @click="currentPage--"
      >
        <el-icon><ArrowLeft /></el-icon>
        上一页
      </el-button>
      <div class="page-indicator">
        第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
      </div>
      <el-button
        class="page-button next-button"
        :disabled="currentPage === totalPages"
        @click="currentPage++"
      >
        下一页
        <el-icon><ArrowRight /></el-icon>
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { ArrowLeft, ArrowRight, Back } from "@element-plus/icons-vue";

// 引入后端API接口
import { selectDoctorByDepartmentAndDate } from "@/api/api";

const props = defineProps({
  departmentId: {
    type: [String, Number],
    required: true,
  },
  departmentName: {
    type: String,
    required: true,
  },
});

const emit = defineEmits(["doctor-selected", "back"]);

const searchKeyword = ref("");
const currentPage = ref(1);
const pageSize = ref(8);
//存储医生数据
const doctors = ref([]);
const departmentName = ref("");

// 获取医生数据
const fetchDoctors = async () => {
  try {
    const department_id = parseInt(props.departmentId);
    departmentName.value = props.departmentName;
    const today = new Date().toISOString().split("T")[0]; // YYYY-MM-DD

    const response = await selectDoctorByDepartmentAndDate({
      department_id: department_id,
      schedule_date: today,
    });

    console.log(response);

    if (response && response.code == 200) {
      doctors.value = response.data.map((doctor) => ({
        id: doctor.doctor_id,
        name: doctor.doctor_name,
        title: doctor.professional_title,
        remainingCount: doctor.max_patients - doctor.actual_patients,
        avatar: doctor.doctor_avatar,
        departmentId: doctor.department_id,
        isOnline: doctor.max_patients - doctor.actual_patients > 0,
        fee: doctor.standard_price, // 添加费用字段
        location: doctor.location, // 新增诊室位置字段
        schedule_instance_id: doctor.instance_id, // 新增：排班实例ID
      }));
    }
  } catch (error) {
    console.error("获取医生数据失败:", error);
    ElMessage.error("获取医生信息失败，请稍后重试");
  }
};

// 根据科室ID过滤医生
const filteredDoctors = computed(() => {
  let result = doctors.value.filter(
    (doctor) => doctor.departmentId === parseInt(props.departmentId)
  );

  if (searchKeyword.value) {
    result = result.filter(
      (doctor) =>
        doctor.name.includes(searchKeyword.value) ||
        doctor.title.includes(searchKeyword.value)
    );
  }

  return result;
});

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredDoctors.value.length / pageSize.value);
});

// 分页后的医生数据
const pagedDoctors = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredDoctors.value.slice(start, end);
});

// 将医生数据按行分组（每行4个）
const buttonRows = computed(() => {
  const rows = [];
  const items = [...pagedDoctors.value];

  while (items.length > 0) {
    rows.push(items.splice(0, 4));
  }

  return rows;
});

const selectDoctor = (doctor) => {
  emit("doctor-selected", {
    id: doctor.id,
    name: doctor.name,
    title: doctor.title,
    fee: doctor.fee, // 添加费用信息
    location: doctor.location, // 新增诊室位置
    schedule_instance_id: doctor.schedule_instance_id, // 新增：排班实例ID
  });
};

const handleSearch = () => {
  currentPage.value = 1;
};

const goBack = () => {
  emit("back");
};

onMounted(() => {
  fetchDoctors();
});
</script>

<style lang="scss" scoped>
.doctor-selection {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  box-sizing: border-box;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;

  h2 {
    margin: 0;
    color: #1e40af;
    font-size: 28px;
    font-weight: 600;
  }
}

.doctor-buttons {
  margin-bottom: 24px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.button-row {
  display: flex;
  justify-content: flex-start;
  gap: 20px;
  margin-bottom: 20px;
  width: 100%;

  &:last-child {
    margin-bottom: 0;
  }
}

.doctor-button {
  width: calc(25% - 15px);
  min-width: 270px;
  max-width: 280px;
  height: 140px !important;
  padding: 16px;
  border-radius: 16px;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  border: none;
  flex: 0 0 auto;

  &:hover {
    background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
    transform: translateY(-4px);
    box-shadow: 0 10px 25px rgba(59, 130, 246, 0.4);
  }

  .button-content {
    display: flex;
    align-items: flex-start;
    width: 100%;
    height: 100%;
    color: white;
    text-align: left;
  }

  .avatar-container {
    position: relative;
    margin-right: 16px;
    flex-shrink: 0;
  }

  .doctor-avatar {
    width: 70px;
    height: 70px;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid rgba(255, 255, 255, 0.3);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  }

  .online-indicator {
    position: absolute;
    bottom: 4px;
    right: 4px;
    width: 14px;
    height: 14px;
    border-radius: 50%;
    background: #94a3b8;
    border: 2px solid white;

    &.online {
      background: #22c55e;
    }
  }

  .button-text {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;
  }

  .doctor-name {
    font-size: 20px;
    font-weight: 600;
    color: white;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .doctor-title {
    font-size: 14px;
    color: #e6f3ff;
    margin-bottom: 10px;
    background: rgba(255, 255, 255, 0.15);
    padding: 4px 8px;
    border-radius: 12px;
    display: inline-block;
    width: fit-content;
  }

  .doctor-status {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
}

.remaining-container {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 4px;

  .remaining-label {
    color: #e6f3ff;
    font-size: 13px;
  }

  .remaining-count {
    color: #a1e075;
    font-size: 14px;
    font-weight: 600;

    &.low {
      color: #ff6b6b;
      animation: pulse 1.5s infinite;
    }
  }
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.6;
  }
  100% {
    opacity: 1;
  }
}

.pagination-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 30px;
  margin-top: 30px;
  padding-top: 24px;
  border-top: 1px solid #e2e8f0;

  .page-button {
    min-width: 120px;
    height: 44px;
    font-size: 16px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    gap: 6px;

    &.prev-button {
      background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
      color: #475569;
      border: 1px solid #cbd5e1;

      &:hover:not(:disabled) {
        background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
        transform: translateY(-1px);
      }
    }

    &.next-button {
      background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
      color: white;
      border: none;

      &:hover:not(:disabled) {
        background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
        transform: translateY(-1px);
      }
    }

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
      transform: none !important;
    }
  }

  .page-indicator {
    color: #475569;
    font-size: 16px;
    min-width: 150px;
    text-align: center;
    font-weight: 500;
  }
}

.action-buttons {
  display: flex;
  gap: 12px;

  .back-button {
    background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
    color: #475569;
    border: 1px solid #cbd5e1;
    height: 44px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    gap: 6px;

    &:hover {
      background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
      transform: translateY(-1px);
    }
  }
}

/* 平板设备适配 */
@media (max-width: 1200px) {
  .doctor-selection {
    max-width: 900px;
  }

  .doctor-button {
    width: calc(33.333% - 14px);
    min-width: 220px;
    height: 130px !important;

    .doctor-avatar {
      width: 60px;
      height: 60px;
    }

    .doctor-name {
      font-size: 18px;
    }
  }
}

@media (max-width: 992px) {
  .doctor-selection {
    padding: 18px;
    max-width: 800px;
  }

  .page-header {
    h2 {
      font-size: 24px;
    }
  }

  .button-row {
    gap: 15px;
  }

  .doctor-button {
    width: calc(33.333% - 10px);
    min-width: 200px;
    height: 120px !important;

    .doctor-avatar {
      width: 55px;
      height: 55px;
    }

    .doctor-name {
      font-size: 16px;
    }

    .doctor-title {
      font-size: 13px;
    }
  }
}

/* 移动设备适配 */
@media (max-width: 768px) {
  .doctor-selection {
    padding: 16px;
    max-width: 100%;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    margin-bottom: 20px;

    h2 {
      font-size: 22px;
    }
  }

  .button-row {
    flex-wrap: wrap;
    gap: 12px;
    margin-bottom: 12px;
    justify-content: flex-start;
  }

  .doctor-button {
    width: calc(50% - 6px);
    flex: 0 0 calc(50% - 6px);
    min-width: unset;
    max-width: calc(50% - 6px);
    height: 120px !important;
    padding: 12px;

    .doctor-avatar {
      width: 50px;
      height: 50px;
    }

    .doctor-name {
      font-size: 16px;
    }

    .doctor-status {
      font-size: 12px;
    }
  }

  .pagination-controls {
    flex-direction: column;
    gap: 12px;

    .page-button {
      width: 100%;
      max-width: 200px;
      height: 44px;
    }
  }

  .action-buttons {
    width: 100%;
    justify-content: flex-start;

    .back-button {
      width: 100%;
      max-width: 200px;
    }
  }
}

/* 小屏幕手机适配 */
@media (max-width: 480px) {
  .doctor-selection {
    padding: 12px;
  }

  .page-header {
    h2 {
      font-size: 20px;
    }
  }

  .button-row {
    gap: 8px;
    justify-content: flex-start;
  }

  .doctor-button {
    flex: 0 0 calc(50% - 4px);
    max-width: calc(50% - 4px);
    height: 110px !important;
    padding: 10px;

    .doctor-avatar {
      width: 45px;
      height: 45px;
    }

    .doctor-name {
      font-size: 14px;
    }

    .doctor-title {
      font-size: 12px;
    }
  }
}
</style>